package dict;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class DictFile {
	private String strFileName;// path to the .dict file

	/**
	 * @return strFileName
	 */
	public String getStrFileName() {
		return strFileName;
	}

	/**
	 * @param strFileName
	 *            URI of .dict file
	 */
	public void setStrFileName(String strFileName) {
		this.strFileName = strFileName;
	}

	/**
	 * @param fileName
	 *            URI of .dict file
	 */
	public DictFile(String fileName) {
		this.strFileName = fileName;
	}

	/**
	 * 
	 * @param offset
	 * @param size
	 * @return the word's meaning
	 */
	public String getWordData(long offset, long size) {
		String strMeaning = "not found";
		DataInputStream dt = null;
		byte[] bt = new byte[(int) size];

		if (!((new java.io.File(strFileName)).exists())) {
			return "File: " + strFileName + " does not exist";
		}
		try {
			dt = new DataInputStream(new BufferedInputStream(
					new FileInputStream(strFileName)));
			dt.skip(offset);
			dt.read(bt, 0, (int) size);
			strMeaning = new String(bt, "UTF8");
		} catch (Exception ex) {
		} finally {
			if (dt != null) {
				try {
					dt.close();
				} catch (Exception ex) {
				}
			}
		}
		return strMeaning;
	}

	/**
	 * @param strMeaning
	 *            word's meaning
	 * @return the position of word meanings
	 */
	public long addData(String strMeaning) {
		DataOutputStream dt = null;
		long fileSize = -1;
		
		try {
			File dictFile = new File(strFileName);
			fileSize = dictFile.length();
			dt = new DataOutputStream(new FileOutputStream(strFileName, true));
			dt.write(strMeaning.getBytes("UTF8"));
		} catch (Exception ex) {
		} finally {
			if (dt != null) {
				try {
					dt.close();
				} catch (Exception ex) {
				}
			}
		}
		return fileSize;
	}
}
